import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "微e宝终身重大疾病保险"
    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year":[str( i ) for i in range(0,41)],
                #性别
                "gender":["M","F"],
                #保障金额
                "money":["100000","200000","300000","400000","500000"],
                #交费方式
                "payType":["年交","月交"],
                #交费间隔
                "interval":["10","20"],
                #保障期限
                "expire":["终身"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(41, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["100000", "200000", "300000", "400000", "500000"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 交费间隔
                "interval": ["10"],
                # 保障期限
                "expire": ["终身"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["payType"],plan[k]["interval"],plan[k]["expire"]):
                data = Helper.formatProductInfo( plan[k],v )
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( **data ))
                self.mysql._conn.commit()
                print(  domain[self.name]["insert_sql"].format( **data ) )
    #执行爬虫
    def requestJson(self,dt=None):
        data = {
            "rqstType":"AJAX",
            "chnlId":"23",
            "packageCode":"642020",
            "socialFlag":"2",
            "benefit":"1000",
            "unit":"y",
            "birthday":"{0}-01-01".format( str(int( 2020-int(dt["year"])))),
            "sex":"0" if dt["gender"] == "M" else "1",
            "categoryCode":"300091",
            "dutyListMoney[0][paymentType]":"12" if dt["payType"] == "年交" else "1",
            "dutyListMoney[0][payment]":dt["interval"],
            "dutyListMoney[0][riskCode]":"632001",
            "dutyListMoney[0][cvrAmount]":dt["money"],
            "dutyListMoney[0][dutyCode]":"632100",
            "dutyListMoney[0][mainRiskCode]":"632001",
        }
        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload,verify=False)
        if r.status_code == 200 and "成功" in r.text:
            price = r.json()["defmap"]["price"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*保险产品价格更新失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
